package com.hanoi.wiki.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hanoi.wiki.dao.LogDAO;
import com.hanoi.wiki.dao.PlacesDAO;
import com.hanoi.wiki.dao.PlacesInQueuedDAO;
import com.hanoi.wiki.exception.DataAccessException;
import com.hanoi.wiki.manager.LogManager;
import com.hanoi.wiki.model.Log;
import com.hanoi.wiki.model.Places;
import com.hanoi.wiki.model.PlacesInQueued;
import com.hanoi.wiki.model.json.LogJson;

@Component
@Transactional
public class LogManagerImpl extends BaseManagerImpl implements LogManager{
	
	@Autowired
	private LogDAO logDAO;

	@Autowired
	private PlacesDAO placesDAO;
	
	@Autowired
	private PlacesInQueuedDAO inQueuedDAO;
	
	public int save(LogJson json) {
		try {
			Log log = new Log(json);
			
			Places place = placesDAO.get(json.getPlaces());
			if(place != null) {
				log.setPlaces(place);
			}
			
			PlacesInQueued inQueued = inQueuedDAO.get(json.getPlacesInQueued());
			if(inQueued != null) {
				log.setPlacesInQueued(inQueued);
			}
			
			return logDAO.saveLog(log);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	public void update(LogJson json) {
		try {
			Log log = new Log(json);
			
			log.setId(json.getId());
			Places place = placesDAO.get(json.getPlaces());
			if(place != null) {
				log.setPlaces(place);
			}
			
			PlacesInQueued inQueued = inQueuedDAO.get(json.getPlacesInQueued());
			if(inQueued != null) {
				log.setPlacesInQueued(inQueued);
			}
			
			logDAO.update(log);
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public LogJson get(Integer id) {
		try {
			return new LogJson(logDAO.get(id));
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public List<LogJson> getList() {
		List<LogJson> logJsonList = new ArrayList<LogJson>();
		List<Log> logList = logDAO.getList();
		try {
			for(Log log : logList) {
				logJsonList.add(new LogJson(log));
			}
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return logJsonList;
	}

	public void remove(Integer id) {
		try {
			if(logDAO.get(id) != null) {
				logDAO.remove(id);
			}
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
